package com.software.frontend.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.software.frontend.R;
import com.software.frontend.firstPage.fragment.RecFragment;
import com.software.frontend.loginAndRegist.LoginByPhoneAndPasswordActivity;
import com.software.frontend.loginAndRegist.entity.UserExtends;
import com.software.frontend.mine.activity.LargeImageActivity;
import com.software.frontend.mine.activity.NoticeDetails;
import com.software.frontend.mine.activity.SettingsActivity;
import com.software.frontend.mine.utils.DownLoadImageTask;
import com.software.frontend.mine.utils.PictureProcessUtils;
import com.software.frontend.searchmovie.activity.SearchMovieRequestActivity;

import okhttp3.OkHttpClient;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Mine_MainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Mine_MainFragment extends Fragment {

    ImageView head;
    ConstraintLayout notices;
    LinearLayoutCompat search, settings;
    LinearLayout likeNumberLinaer, attentionsNumberLinaer, fansNumberLinaer, postNumberLinear;
    TextView likeNumber, attentionsNumber, fansNumber, postNumber, noticesNumber;
    TextView userName, userAccount, significance;
    LinearLayout background, draftsVideo, productsVideo, attentionsVideo, likesVideo;
    FrameLayout fragment;
    Bitmap head_bitmap;
    private String getheadServiceUrl = "center/getHead";
    private OkHttpClient okHttpClient = new OkHttpClient();
    private Gson gson = new Gson();
    public static final int RESULT_OK = 1;
    public static final int RESULT_CANCLE = 0;
    public static final int RESULT_ERROR = 500;
    public static final int HEAD_IMAGE_RESULT_CODE_SUCCESS = 1;
    public static final int HEAD_IMAGE_RESULT_CODE_FAILD = -1;
    RecFragment draftRecFragment, postRecFragment, likesRecFragment, attentionRecFragment;
    private final Handler handler = new Handler(Looper.myLooper()){
        @SuppressLint("UseCompatLoadingForDrawables")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.arg1 == 0){
                setmUserExtends(null);
            }else if (msg.arg1 == HEAD_IMAGE_RESULT_CODE_SUCCESS){
                if (mUserExtends != null){
                    Bundle bundle = msg.getData();
                    head_bitmap = bundle.getParcelable("bitmap");
                    background.setBackground(new BitmapDrawable(head_bitmap));
                    head.setImageBitmap(PictureProcessUtils.toRoundBitmap(head_bitmap));
                }else {
                    background.setBackgroundColor(getResources().getColor(R.color.white));
                    head.setImageDrawable(getResources().getDrawable(R.drawable.person_head));
                }
            }else if (msg.arg1 == HEAD_IMAGE_RESULT_CODE_FAILD){
                Toast.makeText(getContext(), "很抱歉，头像加载出错啦，换个姿势试试叭", Toast.LENGTH_SHORT).show();
                background.setBackgroundColor(getResources().getColor(R.color.white));
                head.setImageDrawable(getResources().getDrawable(R.drawable.person_head));
            }
        }
    };
    private final DownLoadImageTask downLoadImageTask = new DownLoadImageTask(handler, 1, -1);

    public void setmUserExtends(UserExtends mUserExtends) {
        this.mUserExtends = mUserExtends;
        if (mUserExtends == null){
            head_bitmap = null;
        }
        initViews();
        setListeners();
    }

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String USERSEXTENDS = "usersExtends";

    // TODO: Rename and change types of parameters
    private UserExtends mUserExtends;

    public Mine_MainFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param userExtends 传入用户个人信息
     * @return A new instance of fragment Mine_MainFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Mine_MainFragment newInstance(UserExtends userExtends) {
        Mine_MainFragment fragment = new Mine_MainFragment();
        Bundle args = new Bundle();
        args.putSerializable(USERSEXTENDS, userExtends);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mUserExtends = (UserExtends) getArguments().getSerializable(USERSEXTENDS);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_mine__main, container, false);
        bindingViews(inflate);
        initViews();
        setListeners();
        initFragments();
        return inflate;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK){
            UserExtends userExtends = (UserExtends)data.getSerializableExtra("resultData");
            head_bitmap = gson.fromJson(data.getStringExtra("head"), Bitmap.class);
            if (head_bitmap != null){
                head.setImageBitmap(PictureProcessUtils.toRoundBitmap(head_bitmap));
            }
            if (userExtends != null){
                setmUserExtends(userExtends);
            }
        }if (resultCode == 3){
            setmUserExtends(null);
        }
    }

    @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
    private void initViews() {
        if (mUserExtends != null) {
            userName.setText(mUserExtends.getName());
            userAccount.setText("剪影号：" + mUserExtends.getId().toString());
            //头像解析和展示////////////////////////////////
            if (head_bitmap == null){
                downLoadImageTask.execute(getResources().getString(R.string.localhost) + getResources().getString(R.string.head_request_path) + mUserExtends.getId() + "/" + mUserExtends.getAvatarUrl());
            }
            //通知的计算和展示
            noticesNumber.setVisibility(View.VISIBLE);
            likeNumber.setText(mUserExtends.getLikeCount().toString());
            fansNumber.setText(mUserExtends.getFollowerCount().toString());
            attentionsNumber.setText(mUserExtends.getAttentionCount().toString());
            postNumber.setText(mUserExtends.getPostCount().toString());
            significance.setText(mUserExtends.getIntroduction());
            ((TextView)(draftsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.selected));
        }else {
            System.out.println(1111);
            userName.setText(null);
            userAccount.setText(null);
            background.setBackgroundColor(getResources().getColor(R.color.white));
            head.setImageDrawable(getResources().getDrawable(R.drawable.person_head));
            noticesNumber.setVisibility(View.INVISIBLE);
            likeNumber.setText(null);
            fansNumber.setText(null);
            attentionsNumber.setText(null);
            postNumber.setText(null);
            significance.setText(null);
            ((TextView)(draftsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
            ((TextView)(likesVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
            ((TextView)(attentionsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
            ((TextView)(productsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
        }
    }

    private void setListeners() {
        //情况1，MUserExtends为空，为登陆，只注册登陆跳转和登陆提示
        if (mUserExtends == null){
            //登陆跳转
            View.OnClickListener onClickSkipToLogin = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), LoginByPhoneAndPasswordActivity.class);
                    startActivity(intent);
                }
            };
            head.setOnClickListener(onClickSkipToLogin);
            userName.setOnClickListener(onClickSkipToLogin);
            //登陆提示
            View.OnClickListener clickToToast = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), "抱歉，请先登录", Toast.LENGTH_SHORT).show();
                }
            };
            notices.setOnClickListener(clickToToast);
            likeNumberLinaer.setOnClickListener(clickToToast);
            attentionsNumberLinaer.setOnClickListener(clickToToast);
            fansNumberLinaer.setOnClickListener(clickToToast);
            postNumberLinear.setOnClickListener(clickToToast);
            draftsVideo.setOnClickListener(clickToToast);
            productsVideo.setOnClickListener(clickToToast);
            attentionsVideo.setOnClickListener(clickToToast);
            likesVideo.setOnClickListener(clickToToast);
            significance.setOnClickListener(clickToToast);
        }else {
            //情况2，没UserExtends不为空，已登录
            //注册通知按钮
            View.OnClickListener noticesPoint = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noticesNumber.setVisibility(View.INVISIBLE);
                    Intent intent = new Intent(getActivity(), NoticeDetails.class);
                    startActivity(intent);
                    Toast.makeText(getActivity(), "notices跳转", Toast.LENGTH_SHORT).show();
                }
            };
            notices.setOnClickListener(noticesPoint);
            //注册头像点击显示大图
            head.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), LargeImageActivity.class);
                    Bitmap bitmap = ((BitmapDrawable) head.getDrawable()).getBitmap();
                    intent.putExtra("head", gson.toJson(bitmap));
                    startActivity(intent);
                }
            });
            //注册数量按钮点击事件
            View.OnClickListener countlistOnClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    //四项，点击跳转////////////////////////
//                    Intent intent = new Intent(getActivity(), SocialList.class);
//                    switch (v.getId()) {
//                        case R.id.mine_main_linerLayout_guanzhu:
//                            intent.putExtra("type", "attention");
//                            break;
//                        case R.id.mine_main_linerLayout_post:
//                            intent.putExtra("type", "post");
//                            break;
//                        case R.id.mine_main_linerLayout_fensi:
//                            intent.putExtra("type", "fans");
//                            break;
//                    }
//                    startActivity(intent);
                }
            };
            attentionsNumberLinaer.setOnClickListener(countlistOnClickListener);
            fansNumberLinaer.setOnClickListener(countlistOnClickListener);
            postNumberLinear.setOnClickListener(countlistOnClickListener);
            //注册视频栏目点击监听
            View.OnClickListener videosTypeList = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    //下四项，点击切换界面////////////////////////
                    setButtonsDefautFormat();
                    switch (v.getId()) {
                        case R.id.mine_main_video_drafts:
                            ((TextView)(draftsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.selected));
                            getChildFragmentManager()
                                    .beginTransaction()
                                    .show(draftRecFragment)
                                    .hide(postRecFragment)
                                    .hide(attentionRecFragment)
                                    .hide(likesRecFragment)
                                    .commit();
                            break;
                        case R.id.mine_main_video_production:
                            ((TextView)(productsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.selected));
                            getChildFragmentManager()
                                    .beginTransaction()
                                    .hide(draftRecFragment)
                                    .show(postRecFragment)
                                    .hide(attentionRecFragment)
                                    .hide(likesRecFragment)
                                    .commit();
                            break;
                        case R.id.mine_main_video_like:
                            ((TextView)(likesVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.selected));
                            getChildFragmentManager()
                                    .beginTransaction()
                                    .hide(draftRecFragment)
                                    .hide(postRecFragment)
                                    .hide(attentionRecFragment)
                                    .show(likesRecFragment)
                                    .commit();
                            break;
                        case R.id.mine_main_video_attion:
                            ((TextView)(attentionsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.selected));
                            getChildFragmentManager()
                                    .beginTransaction()
                                    .hide(draftRecFragment)
                                    .hide(postRecFragment)
                                    .show(attentionRecFragment)
                                    .hide(likesRecFragment)
                                    .commit();
                            break;
                    }
                }

                private void setButtonsDefautFormat() {
                    ((TextView)(draftsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
                    ((TextView)(attentionsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
                    ((TextView)(likesVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
                    ((TextView)(productsVideo.getChildAt(0))).setTextColor(getResources().getColor(R.color.black));
                }
            };
            draftsVideo.setOnClickListener(videosTypeList);
            attentionsVideo.setOnClickListener(videosTypeList);
            likesVideo.setOnClickListener(videosTypeList);
            productsVideo.setOnClickListener(videosTypeList);
        }
        //设置搜索按钮点击跳转
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchMovieRequestActivity.class);
                startActivity(intent);
            }
        });
        //设置按钮点击事件
        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出选项卡////////////////////////////////
                Toast.makeText(getActivity(), "弹出选项卡", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), SettingsActivity.class);
                intent.putExtra("userExtends", mUserExtends);
                Bitmap bitmap = ((BitmapDrawable) head.getDrawable()).getBitmap();
                intent.putExtra("head", gson.toJson(bitmap));
                startActivityForResult(intent, 1);
            }
        });
    }

    private void bindingViews(View inflate) {
        userName = (TextView) inflate.findViewById(R.id.mine_main_name);
        userAccount = (TextView) inflate.findViewById(R.id.mine_main_idiograph);
        background = (LinearLayout) inflate.findViewById(R.id.mine_main_background);
        notices = (ConstraintLayout) inflate.findViewById(R.id.mine_main_notices);
        search = (LinearLayoutCompat) inflate.findViewById(R.id.mine_main_search);
        settings = (LinearLayoutCompat) inflate.findViewById(R.id.mine_main_settings);
        head = (ImageView) inflate.findViewById(R.id.mine_main_header);
        likeNumber = (TextView) inflate.findViewById(R.id.mine_main_dianzan);
        attentionsNumber = (TextView) inflate.findViewById(R.id.mine_main_guanzhu);
        fansNumber = (TextView) inflate.findViewById(R.id.mine_main_fensi);
        likeNumberLinaer = (LinearLayout) inflate.findViewById(R.id.mine_main_linerLayout_dianzan);
        attentionsNumberLinaer = (LinearLayout) inflate.findViewById(R.id.mine_main_linerLayout_guanzhu);
        fansNumberLinaer = (LinearLayout) inflate.findViewById(R.id.mine_main_linerLayout_fensi);
        postNumber = (TextView) inflate.findViewById(R.id.mine_main_post);
        postNumberLinear = (LinearLayout) inflate.findViewById(R.id.mine_main_linerLayout_post);
        significance = (TextView) inflate.findViewById(R.id.mine_main_personal_signature);
        draftsVideo = (LinearLayout) inflate.findViewById(R.id.mine_main_video_drafts);
        productsVideo = (LinearLayout) inflate.findViewById(R.id.mine_main_video_production);
        attentionsVideo = (LinearLayout) inflate.findViewById(R.id.mine_main_video_attion);
        noticesNumber = (TextView) inflate.findViewById(R.id.mine_main_notices_count);
        likesVideo = (LinearLayout) inflate.findViewById(R.id.mine_main_video_like);
        fragment = (FrameLayout) inflate.findViewById(R.id.fragment_mine_main);
    }

    private void initFragments() {

        draftRecFragment = RecFragment.newInstance(null);
        postRecFragment = RecFragment.newInstance(null);
        likesRecFragment = RecFragment.newInstance(null);
        attentionRecFragment = RecFragment.newInstance(null);
            getChildFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_mine_main, draftRecFragment)
                .add(R.id.fragment_mine_main, postRecFragment)
                .hide(postRecFragment)
                .add(R.id.fragment_mine_main, attentionRecFragment)
                .hide(attentionRecFragment)
                .add(R.id.fragment_mine_main, likesRecFragment)
                .hide(likesRecFragment)
                .commit();
    }
}